/**
 * 
 */
package co.fitstart.admin.web.controller.trade.product;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;

import co.fitstart.admin.service.DataService;
import co.fitstart.admin.service.ProductService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.entity.coupon.CouponTemplate;
import co.fitstart.entity.coupon.DiscountType;
import co.fitstart.entity.course.Course;
import co.fitstart.entity.product.Product;
import co.fitstart.entity.product.ProductCategory;
import co.fitstart.entity.product.ProductType;
import co.fitstart.entity.product.Status;

/**
 * @author downpour
 * @author mohanlan
 *
 */
@Controller
@MenuSetting("menu-ecommerce")
@RequestMapping("/products")
public class ProductCreateController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProductCreateController.class);
    
    @Autowired
    private DataService<Course> dataService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    /**
     * Display create online product panel
     * 
     * @return
     */
    @RequestMapping(value = "/online-product/create", method = RequestMethod.GET)
    @MenuSetting("submenu-product-management")
    public String createOnlineProduct(){
        return "ecommerce/product/create/online-product-create";
    }
    
    /**
     * Do create online product
     * 
     * @param courseId 
     * @return
     */
    @RequestMapping(value = "/online-product", method = RequestMethod.POST)
    public @ResponseBody String onCreateOnlineProduct(@RequestParam("course") Long courseId){
        
        Result result = new Result();
        
        try {
            
            Course course = dataService.load(Course.class, courseId);
            Product latestProduct = productService.loadLatestProduct(course);
            Product product = productService.create(latestProduct);
            
            result.success()
                  .message("创建产品成功").data("url", "/products/online-product/initialize?productId=" + product.getId());
            
        } catch (Exception e) {
            
            logger.error("#onCreateOnlineProduct ", e);
            result.fail().message("创建产品失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param productId
     * @return
     */
    @RequestMapping(value = "/online-product/initialize", method = RequestMethod.GET)
    @MenuSetting("submenu-product-management")
    public ModelAndView initializeOnlineProduct(@RequestParam("productId") Long productId){
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/product/create/online-product-initialize");
        
        Product product = productService.load(Product.class, productId);
        modelAndView.addObject("product", product);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param product
     * @param inputTags 
     * @return
     */
    @RequestMapping(value = "/online-product/initialize", method = RequestMethod.PATCH)
    public ModelAndView onInitializeOnlineProduct(@Preloading("productId") Product product,
                                                  @RequestParam(value = "inputTags", required = false) List<String> inputTags) {
        
        ModelAndView modelAndView = new ModelAndView();
        
        try {
            
            productService.edit(product.edit(), inputTags);
            
            modelAndView.setViewName("redirect:/products");
            
        } catch (Exception e) {
            logger.error("onInitializeOnlineProduct() error: ", e);
            modelAndView.setViewName("ecommerce/product/create/online-product-initialize");
            modelAndView.addObject("errorMessage", "编辑失败");
            return modelAndView;
        }
        
        return modelAndView;
    }
    
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/online-year-product/create", method = RequestMethod.GET)
    @MenuSetting("submenu-product-management")
    public ModelAndView createOnlineYearProduct(){
        ModelAndView modelAndView = new ModelAndView("ecommerce/product/create/online-year-product-create");
        
        modelAndView.addObject("status", Status.EDITING);
        modelAndView.addObject("productType", ProductType.ONLINE);
        
        ProductCategory defaultCategory = genericDaoSupport.searchForObject("FROM ProductCategory WHERE name = :name", "name", "线上年卡", ProductCategory.class);
        modelAndView.addObject("defaultCategory", defaultCategory);
        
        List<CouponTemplate> couponBatchs = genericDaoSupport.searchForList("FROM CouponBatch WHERE couponTemplate.discountType = :percent AND couponTemplate.disabled = false", "percent", DiscountType.PERCENT);
        modelAndView.addObject("couponBatchs", couponBatchs);
        
        return modelAndView;
    }
    
    /**
     * Do create online product
     * 
     * @param courseId 
     * @return
     */
    @RequestMapping(value = "/online-year-product", method = RequestMethod.POST)
    public ModelAndView onCreateOnlineYearProduct(Product product){
        ModelAndView modelAndView = new ModelAndView();
        
        try {
            productService.save(product.initializeOnlineYear());
            modelAndView.setViewName("redirect:/products");
        } catch (Exception e) {
            logger.error("#onCreateOnlineYearProduct ", e);
            modelAndView.setViewName("ecommerce/product/create/online-year-product-create");
            modelAndView.addObject("errorMessage", "创建线上年卡产品失败");
        }
        
        return modelAndView;
    }
}